<!--供应商区分-->
<template>
  <div>
    <cus-search>
      <cus-search-item>
        <Form :model="form" :label-width="80" ref="formValidate" @keydown.native.enter.prevent="onInit">
          <FormItem label="创建时间" class="mr_48 mb_20">
            <DatePicker type="daterange" show-week-numbers transfer ref="formDate" @on-change="datePickerChange"
              placement="bottom-end" placeholder="开始日期 - 结束日期" />
          </FormItem>
          <FormItem label="供应商" :label-width="65" class="mr_48 mb_20" prop="supplierName">
            <Input placeholder="请输入供应商" maxlength="20" clearable v-model="form.supplierName" />
          </FormItem>
          <FormItem label="供应种类" class="mr_48 mb_20" prop="materialClass">
            <Select v-model="form.materialClass" clearable placeholder="全部" style="width: 200px">
              <Option value="">全部</Option>
              <Option v-for="(item, index) in materialClassTree" :value="item.categoryName" :key="item.id">
                {{ item.categoryName }}</Option>
            </Select>
          </FormItem>
          <Button class="mr_24 mb_20"  type="primary" @click="
            pages.page = 1;
          getPurchasingSurchasingListApi();
                        ">查询</Button>
          <Button class="mr_24 mb_20"  type="default" @click="reset">重置</Button>
        </Form>
      </cus-search-item>
    </cus-search>
    <div class="content-bottom">
    <cus-card  :showTitle="false" class="mt_20" style="padding: 20px 20px">
      <div class="btnBox">
        <Button class="mr_24" type="primary" v-permission="20" @click="onAdd()" ghost >添加</Button>
        <Button class="mr_24" type="primary" v-permission="50" @click="importExcel()">导入</Button>
        <Button type="primary" @click="exportChange()" >导出</Button>
      </div>
      <cusTable border :loading="loading" :columns="columns" :data="data" :size="vuex_config.tableSize"
      :bottomClass="['cus-page']">
        <template slot-scope="{ row }" slot="certificationPictureOperation">
          <div style="height: 40px; width: 80px;margin:auto;">
            <viewer ref="viewer" :images="row.certificationPicture">
              <div v-for="(item, index) in row.certificationPicture" :key="index"
                style="height: 40px; width: 80px;margin:auto;">
                <img :src="item.img" alt="" style="width: 100%; height: 100%" />
              </div>
            </viewer>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="status">
                    <div :style="`color: ${row.status == 0 ? '#00aa5a' : '#ff4746'}`">{{ row.status == 0 ? '供应' : '停供'}}</div>
                </template>
                <template slot-scope="{ row }" slot="operation">
                    <div class="flex" style="justify-content: space-around">
                        <Button v-permission="30" type="primary" size="small" @click="onEdit(row)">
                            编辑
                        </Button>
                        <Poptip
                confirm
                transfer
                placement="left"
                :title=" row.status == 1 ?  `是否确认启用${row.name}供应商` : `禁用后所供应商品由自购供应`"
                @on-ok="onStatus(row)"
              >
                        <Button v-permission="40" :type="row.status == 0 ? 'error' : 'success'"  size="small"
                          >
                            {{ row.status == 1 ? "启用" : "禁用" }}
                        </Button>
                        </Poptip>
                    </div>
                </template>
      </cusTable>
      <div class="cus_page">
        <cus-page :data="pages" class="mt_20" @pageChange="getPurchasingSurchasingListApi"></cus-page>
      </div>
    </cus-card>
  </div>
    <!--添加供应商-->
    <addSupplier ref="addSupplier"></addSupplier>
    <!--导入-->
    <cus-uploadModal ref="cusUploadNutritionTagModal" :temp-src="getApiPurchasingDownloadSupplierExcel"
      :uploadFnc="postApiPurchasingExcelImportSupplyInfoDao" titleName="导入供应商"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" @onOk="onInit"
      @onError="onError"></cus-uploadModal>
    <!--excel导入错误提示-->
    <excelErrorModal ref="excelErrorModal"></excelErrorModal>
  </div>
</template>

<script>
import {
  getPurchasingSurchasingList,
  updatePurchasingSupplierDisable,
  getProductCategoryList,
  getApiPurchasingDownloadSupplierExcel,
  postApiPurchasingExcelImportSupplyInfoDao,
  postApiPurchasingExportSupplierExcel
} from "@/api/organ/dishesModule.js";
import addSupplier from "./components/addSupplier.vue";
import excelErrorModal from "./components/excelErrorModal.vue";

const form = {
  id: "",
  startDate: "", // 开始时间
  stopDate: "", // 结束时间
  supplierName: "", // 供应商
  materialClass: "" // 供应种类
};
export default {
  name: "supplierDifferentiation",
  components: { addSupplier, excelErrorModal },
  data() {
    return {
      materialClassTree: [], //供应种类
      form: form,
      getApiPurchasingDownloadSupplierExcel: getApiPurchasingDownloadSupplierExcel, // excel下载地址
      postApiPurchasingExcelImportSupplyInfoDao, // 导入
      data: [],
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      },
      columns :[
  {
    title: "序号",
    type: "index",
    width: 70,
    align: "center"
  },
  {
    title: "供应商编码",
    minWidth: 120,
    key: "supplyCode",
    align: "center"
  },
  {
    title: "供应商名称",
    minWidth: 120,
    key: "name",
    align: "center"
  },
  {
    title: "供应种类",
    minWidth: 120,
    key: "materialClass",
    align: "center"
  },
  {
    title: "资质",
    minWidth: 120,
    align: "center",
    slot: "certificationPictureOperation"
  },
  {
    title: "联系人",
    minWidth: 120,
    key: "contact",
    align: "center"
  },
  {
    title: "联系电话",
    minWidth: 120,
    key: "mobile",
    align: "center"
  },
  {
    title: "地址",
    minWidth: 120,
    key: "address",
    align: "center"
  },
  {
    title: "邮箱",
    minWidth: 120,
    key: "email",
    align: "center"
  },
  {
    title: "创建时间",
    minWidth: 100,
    key: "createTime",
    align: "center"
  },
  {
    title: "状态",
    minWidth: 120,
    align: "center",
     slot: "status"
  },
  {
    title: "操作",
    width: 180,
    fixed: "right",
    slot: "operation",
    align: "center"
  }
],
      loading: false,
      tableHeight: 0
    };
  },
  mounted() {
    this.onInit();
    window.addEventListener("resize", this.getTableHeight);
    this.getTableHeight();
  },
  destroyed() {
    window.removeEventListener("resize", this.tableHeightChange, true);
  },
  methods: {
    //设置Table表头高度自适应
    getTableHeight() {
      this.tableHeight = window.innerHeight - 373;
    },
    reset() {
      this.$refs["formValidate"].resetFields();
      this.$refs.formDate.handleClear(); //清空时间
    },
    onInit() {
      this.pages.page = 1
      this.getPurchasingSurchasingListApi();
      this.getgetProductCategoryListApi();
    },
    datePickerChange(date) {
      (this.form.startDate = date[0]), // 开始时间
        (this.form.stopDate = date[1]), // 结束时间
        this.getPurchasingSurchasingListApi();
    },
    onAdd() {
      this.$refs["addSupplier"].show();
      this.$refs["addSupplier"].uploadList = [];
    },
    //下载供应商列表
    exportChange() {
    this.postApiPurchasingExportSupplierExcelApi()
    },
        // 导出食材清单接口
     postApiPurchasingExportSupplierExcelApi() {
      this.$cu.showLoading();
      return new Promise((resolve) => {
        postApiPurchasingExportSupplierExcel({
          startDate: this.form.startDate ? this.form.startDate : '',
          stopDate: this.form.stopDate ?  this.form.stopDate : '', 
          supplierName: this.form.supplierName ? this.form.supplierName : '',
          materialClass: this.form.materialClass ? this.form.materialClass : '', 
        }).then((res) => {
          console.log(1111);
          this.$cu.hideLoading(1);
          this.$Message.success("供应商清单导出成功.");
          let blob = new Blob([res], { type: `application/vnd.ms-excel` });
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = "供应商清单列表";
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
          resolve();
        });
      });
    },
    importExcel() {
      this.$refs["cusUploadNutritionTagModal"].show();
    },
    onEdit(row) {
      console.log('----------',row);
      row.email  =    row.email == null ? '' :   row.email
      let array = [];
      let startTime = null;
      let stopTime = null;
      this.$refs["addSupplier"].show();
      if (
        row.startTime != null &&
        row.startTime != "" &&
        row.stopTime != null &&
        row.stopTime != ""
      ) {
        startTime = `${new Date(row.startTime).Format("yyyy-MM-dd")}`;
        stopTime = `${new Date(row.stopTime).Format("yyyy-MM-dd")}`;
        array.push(startTime, stopTime);
      }
      let uploadList = [];
      row.certificationPicture.forEach(element => {
        uploadList.push(element.img + "");
      });
      this.$refs["addSupplier"].form = this.$cu.deepClone(row);
      // this.$nextTick(() => {
        row.materialClassValue = row.materialClassValue.map(Number)
        console.log( row.materialClassValue);
        this.$refs["addSupplier"].form.materialClassValue = this.$cu.deepClone(
          row.materialClassValue
        );
        this.$refs["addSupplier"].dateTime = this.$cu.deepClone(array);
        // this.$refs["addSupplier"].form.startTime = this.$cu.deepClone(array[0]);
        // this.$refs["addSupplier"].form.stopTime = this.$cu.deepClone(array[1]);
        this.$refs["addSupplier"].uploadList = uploadList;
      // });
    },
    // 更改状态
    onStatus(row) {
      this.updatePurchasingSupplierDisableApi(row.id);
    },
    onError(data) {
      if(data) {
        this.$refs["excelErrorModal"].show();
      this.$refs["excelErrorModal"].data = data.data;
      }

    },
    // 供应商区分/table列表数据--------------接口
    getPurchasingSurchasingListApi() {
      return new Promise(resolve => {
        let params = {
          startDate: this.form.startDate,
          stopDate: this.form.stopDate,
          supplierName: this.form.supplierName,
          materialClass: this.form.materialClass,
          current: this.pages.page,
          size: this.pages.pageSize
        };
        getPurchasingSurchasingList(params).then(res => {
          this.loading = false;
          if (res.code == 1) {
            this.data = res.data.list;
            this.data.forEach(element => {
              element.certificationPicture = [];
              element.uploadFiles = [];
              if (
                element.certificationPicture1 != null &&
                element.certificationPicture1 != ""
              ) {
                element.certificationPicture.push({
                  img: element.certificationPicture1
                });
              }
              if (
                element.certificationPicture2 != null &&
                element.certificationPicture2 != ""
              ) {
                element.certificationPicture.push({
                  img: element.certificationPicture2
                });
              }
              if (
                element.certificationPicture3 != null &&
                element.certificationPicture3 != ""
              ) {
                element.certificationPicture.push({
                  img: element.certificationPicture3
                });
              }
            });
            this.pages.pageTotal = res.data.total;
            resolve();
          }
        });
      });
    },
    // 更新状态--------------------------接口
    updatePurchasingSupplierDisableApi(id) {
      this.loading = true;
      return new Promise(resolve => {
        updatePurchasingSupplierDisable({ id: id }).then(res => {
          this.loading = false;
          if (res.code == 1) {
            this.onInit();
            resolve();
          }
        });
      });
    },
    // 食材类型接口
    getgetProductCategoryListApi() {
      return new Promise(resolve => {
        getProductCategoryList().then(res => {
          if (res.code == 1) {
            this.materialClassTree = res.data;
            resolve();
          }
        });
      });
    }
  },
  watch: {},
  computed: {}
};
</script>
<style lang="less" scoped>
.btnBox {
  padding-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
